//
//  StoreVCHelper.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/2.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

enum StoreError: Error {
    case NetWorkError
    
}
enum StoreStatus: Int {
    case Failure
    case Success
    case Auditting
}

class StoreVCHelper {
    
    let queue = DispatchQueue(label: "storeVCQueue")
    
    func dataRequest(from request: StoreRequest) -> DataRequest {
        //return Alamofire.request(request.fullURL, method: .post, parameters: request.bodyParams, encoding: URLEncoding.httpbody)
        return Alamofire.request(request.fullURL, method: request.method, parameters: request.bodyParams, encoding: URLEncoding.httpBody, headers: nil)
        //return Alamofire.request(request.fullURL, method: request.method, parameters: request.bodyParams, encoding: URLEncoding.httpbody, headers: nil)
    }
    
    /// 新建SessionId
    ///
    /// - Parameters:
    ///   - phone: userPhone
    ///   - completeHandler: 返回Bool
    func createSessionId(with phone: String, completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.createSessionId
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let sessionId = json["data"]["sessionId"].string!
            Store.sessionID = sessionId
            DispatchQueue.main.async {
                completeHandler(true)
            }
        }
        
    }
    
    func createStore(completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.store
        dataRequest(from: request).responseJSON { (response) in
            guard let _ = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            completeHandler(true)
        }
    }
    
    func applyForSeller(with alias: String, name: String, address: String, mainBusiness: String, foundTime: String, license: String, logo: String, completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.createstore(alias: alias, name: name, address: address, mainBusiness: mainBusiness, foundTime: foundTime, license: license, logo: logo)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let storeId = json["data"]["storeId"].int!
            Store.storeId = storeId
            Store.alias = alias
            Store.name = name
            Store.address = address
            Store.mainBusiness = mainBusiness
            Store.foundTime = foundTime
            Store.license = license
            Store.logo = logo
            DispatchQueue.main.async {
                completeHandler(true)
            }
        }
    }
    
    
    
    /// status: 0代表失败，1代表成功，2代表审核中
    ///
    /// - Parameter completeHandler: 返回String类型的Reason
    func authenticate(completeHandler: @escaping (Bool, StoreStatus?, String?) -> Void) {
        let request = StoreRequest.authenticate
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil, nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["data"]["status"].int!
            let reason = json["data"]["reason"].string
            DispatchQueue.main.async {
                completeHandler(true, StoreStatus(rawValue: status), reason)
            }
        }
    }
    
    ///
    ///
    /// - Parameter completeHandler: 第一个表示请求是否成功，第二个表示是否有商店
    func exist(completeHandler: @escaping (Bool, Bool?) -> Void) {
        let request = StoreRequest.exist
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            if let storeId = json["data"]["storeId"].int {
                Store.storeId = storeId
                Store.authority = json["data"]["authority"].int!
                completeHandler(true, true)
            } else {
                completeHandler(true, false)
            }
        }
    }
    
    private func prepareJSON(data: JSON) {
        Store.alias = data["alias"].string
        Store.name = data["name"].string
        Store.address = data["address"].string
        Store.mainBusiness = data["mainBusiness"].string
        Store.foundTime = data["foundTime"].string
        Store.license = data["license"].string
        Store.logo = data["logo"].string
        Store.contact = data["contact"].string
        Store.phone = data["phone"].string
        Store.telephone = data["telephone"].string
        Store.description = data["description"].string
    }
    
    /// <#Description#>
    ///
    /// - Parameter completeHandler: <#completeHandler description#>
    func find(completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.find
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let data = json["data"]
            self.prepareJSON(data: data)
            DispatchQueue.main.async {
                completeHandler(true)
            }
        }
        
    }
    
    func edit(parameters: Parameters, completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.edit(parameters: parameters)
        print(parameters)
        print(request)
        dataRequest(from: request).responseJSON { (response) in
            print(response.result.error ?? "error")
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            print(json["errmsg"])
            print(json["status"])
            if status == 200 {
                DispatchQueue.main.async {
                    completeHandler(true)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
            }
        }
    }
    
    /// 客户查看商店
    ///
    /// - Parameter completeHandler:
    func visit(completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.find
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let data = json["data"]
            self.prepareJSON(data: data)
            DispatchQueue.main.async {
                completeHandler(true)
            }
        }
    }
    
    func prepareAppState(completeHandler: @escaping (AppState?) -> Void) {
        Store.sessionID = User.sessionID!
        self.exist { (success, exist) in
            if success {
                if exist! {
                    if Store.authority! == 0 { //管理员
                        self.queue.async {
                            self.authenticate { netWork, state, _ in
                                if netWork {
                                    if state == StoreStatus.Success {
                                        DispatchQueue.main.async {
                                            App.state = AppState.AdminState
                                            completeHandler(AppState.AdminState)
                                        }
                                    } else {
                                        DispatchQueue.main.async {
                                            App.state = AppState.ApplyState
                                            completeHandler(AppState.ApplyState)
                                        }
                                    }
                                } else {
                                    DispatchQueue.main.async {
                                        App.state = AppState.none
                                        completeHandler(nil)
                                    }
                                }
                            }
                        }
                    } else {
                        App.state = AppState.MemberState
                        completeHandler(AppState.MemberState)
                    }
                } else {
                    App.state = AppState.ApplyState
                    completeHandler(AppState.ApplyState)
                }
            } else {
                App.state = AppState.none
                completeHandler(nil)
            }
        }
    }
    
    
    /// MARK: 成员管理
    func getAllMembers(completeHandler: @escaping (Bool, [Member]?) -> Void) {
        let request = StoreRequest.allMembers
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            let data = json["data"].array!
            var members = [Member]()
            for member in data {
                let mem = Member(id: member["id"].int!, name: member["name"].string!, memberId: member["memberId"].string!, authority: member["authority"].int!)
                members.append(mem)
            }
            DispatchQueue.main.async {
                completeHandler(true, members)
            }
        }
    }
    func addMember(phone: String, authority: Int, memberName: String, completeHandler: @escaping (Bool, String?) -> Void) {
        let request = StoreRequest.addMember(phone: phone,memberName: memberName, authority: authority)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            if status == 200 {
                DispatchQueue.main.async {
                    completeHandler(true, nil)
                }
            } else {
                DispatchQueue.main.async {
                    //print(json["errmsg"].stringValue)
                    completeHandler(false, json["errmsg"].stringValue)
                }
            }
        }
    }
    func editMember(id: Int, name: String, authority: Int, completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.editMembers(name: name, authority: authority, id: id)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            let status = json["status"].intValue
            if status == 200 {
                DispatchQueue.main.async {
                    completeHandler(true)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
            }
        }
    }
    func deleteMember(id: [Int], completeHandler: @escaping (Bool) -> Void) {
        let request = StoreRequest.deleteMember(memberIds: id)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                if let data = json["errmsg"].dictionary {
                    if data["error_ids"]?.arrayValue.count == 0 {
                        DispatchQueue.main.async {
                            completeHandler(true)
                        }
                    } else {
                        DispatchQueue.main.async {
                            print("count +++ \(json)")
                            completeHandler(false)
                        }
                    }
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
            }
            
        }
    }
    
    
}
